package com.flu.holidays.util;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 根据国务院办公厅公告的节假日信息获取节假日配置信息
 * https://sousuo.www.gov.cn/sousuo/search.shtml
 * 搜 部分节假日安排的通知
 */
public class HolidayUtil {

    /**
     * 获取指定字符串前的数字
     */
    private static final Pattern PATTERN = Pattern.compile("[^\\d]");
    private static String getDigit(String content, String targetStr) {
        if(!content.contains(targetStr)){
            return null;
        }
        content = content.substring(0, content.indexOf(targetStr));
        StringBuffer sb = new StringBuffer(content);
        content = sb.reverse().toString();
        //使用正则表达式匹配第一个非数字
        Matcher matcher = PATTERN.matcher(content);
        if (matcher.find()) {
            content = content.substring(0, matcher.start());
            sb = new StringBuffer(content);
            return sb.reverse().toString();
        }
        //是否为数字
        if(NumberUtil.isNumber(content)){
            return new StringBuffer(content).reverse().toString();
        }
        return null;
    }

    /**
     * 根据年月日字符转为 yyyy-M-d 格式的LocalDate
     * @param year
     * @param month
     * @param day
     * @return
     */
    private static LocalDate parseDate(String year, String month, String day) {
        String dateStr = year + "-" + month + "-" + day;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
        return LocalDate.parse(dateStr, formatter);
    }
    public static void main(String[] args) {

        List<String> holidayTypes = ListUtil.of("元旦","春节","清明节","劳动节","端午节","中秋节","国庆节","五一","十一");

        String year = "2025";
        //获取当前java文件所在目录
        String path = FileUtil.getAbsolutePath("classpath:holiday-source");
        File file = new File(path +File.separator+ year+".txt");
        String message = FileUtil.readString( file, StandardCharsets.UTF_8);
        Map<String,String> holidays = new LinkedHashMap<>(32);
        Map<String,String> shiftChanges = new LinkedHashMap<>(8);
        String[] split = message.split("\n");
        for (String text : split) {
            if ( text.contains("：") && text.contains("。") && text.contains("放假")) {
                //获取假期类型
                String holidayType = holidayTypes.stream().filter(text::contains).findFirst().orElse("");
                text = text.substring(text.indexOf("：")+1);
                //text 根据。或，分隔
                String[] sentences = text.split("[。，]");
                for (String sentence : sentences) {
                    if (sentence.contains("放假")) {
                        String t = sentence.split("放假")[0];
                        if (t.contains("至")||t.contains("—")) {
                            String start = t.split("至")[0];
                            String startDay=null, startMonth=null, startYear=null;
                            if(start.contains("日") || start.contains("月") || start.contains("年")){
                                startDay = getDigit(start, "日");
                                startMonth = getDigit(start, "月");
                                startYear = getDigit(start, "年");
                            }
                            LocalDate startDate = parseDate(startYear==null?year:startYear, startMonth, startDay);
                            String end = t.contains("至")?t.split("至")[1]:t.split("—")[1];
                            String endDay=null, endMonth=null, endYear=null;
                            if(end.contains("日") || end.contains("月") || end.contains("年")){
                                endDay = getDigit(end, "日");
                                endMonth = getDigit(end, "月");
                                endYear = getDigit(end, "年");
                            }
                            LocalDate endDate = parseDate(endYear==null?(startYear==null?year:startYear):endYear, endMonth==null?startMonth:endMonth, endDay);
                            for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
                                holidays.put(date.toString(),holidayType);
                            }
                        } else {
                            String tDay=null, tMonth=null, tYear=null;
                            if(t.contains("日") || t.contains("月") || t.contains("年")){
                                tDay = getDigit(t, "日");
                                tMonth = getDigit(t, "月");
                                tYear = getDigit(t, "年");
                            }
                            LocalDate date = parseDate(tYear==null? year:tYear, tMonth, tDay);
                            holidays.put(date.toString(),holidayType);
                        }
                    }
                    if (sentence.contains("上班")) {
                        String t = sentence.split("上班")[0];
                        if (sentence.contains("、")) {
                            String[] dates = sentence.split("、");
                            String month = null;
                            for (String dateStr : dates) {
                                String tDay=null, tMonth=null, tYear=null;
                                if(dateStr.contains("日") || dateStr.contains("月") || dateStr.contains("年")){
                                    tDay = getDigit(dateStr, "日");
                                    tMonth = getDigit(dateStr, "月");
                                    if (tMonth == null){
                                        tMonth = month;
                                    }else {
                                        month = tMonth;
                                    }
                                    tYear = getDigit(dateStr, "年");
                                }
                                LocalDate date = parseDate(tYear==null? year:tYear, tMonth, tDay);
                                shiftChanges.put(date.toString(),holidayType);
                            }
                        }else{
                            String tDay=null, tMonth=null, tYear=null;
                            if(t.contains("日") || t.contains("月") || t.contains("年")){
                                tDay = getDigit(t, "日");
                                tMonth = getDigit(t, "月");
                                tYear = getDigit(t, "年");
                            }
                            LocalDate date = parseDate(tYear==null? year:tYear, tMonth, tDay);
                            shiftChanges.put(date.toString(),holidayType);
                        }
                    }
                }
            }
        }
        holidays.forEach(( holiday,holidayType) -> {
            //System.out.println( "- "+holiday);
            String formatDt = DateUtil.format(DateUtil.parse(holiday, DatePattern.NORM_DATE_FORMATTER), DatePattern.PURE_DATE_FORMATTER);
            //生成holiday表的insert语句
            System.out.println("insert into holiday (id,year,dt,holiday_type,type,create_time) values ("+ IdUtil.getSnowflakeNextId()+"," +year+","+formatDt+",\""+holidayType+"\",1,now());");
        });
        System.out.println("====================================");
        shiftChanges.forEach(( shiftChange,shiftChangeType) -> {
            String formatDt = DateUtil.format(DateUtil.parse(shiftChange, DatePattern.NORM_DATE_FORMATTER), DatePattern.PURE_DATE_FORMATTER);
            System.out.println("insert into holiday (id,year,dt,holiday_type,type,create_time) values ("+ IdUtil.getSnowflakeNextId()+"," +year+","+formatDt+",\""+shiftChangeType+"\",0,now());");
        });


    }




}
